﻿using System;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utility.Windows.Forms
{
    public class DataGridView : System.Windows.Forms.DataGridView
    {
        #region 构造函数
        public DataGridView()
        {
        }
        #endregion

        #region 方法
        #region SetDataBinding
        public void SetDataBinding(DataTable dataTable, ArrayList columnsToShow, ArrayList readOnlyColumns, bool allowNewRows, bool allowDeleteRows)
        {
            this.DataSource = dataTable;
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                this.Columns[i].HeaderText = dataTable.Columns[i].Caption;
                if (!this.IsColumnExist(dataTable.Columns[i].ColumnName, columnsToShow))
                {
                    this.Columns[i].Visible = false;
                }
                if (this.IsColumnExist(dataTable.Columns[i].ColumnName, readOnlyColumns))
                {
                    this.Columns[i].ReadOnly = true;
                }
            }

            if (allowNewRows == false)
            {
                this.AllowUserToAddRows = false;
            }
            if (allowDeleteRows == false)
            {
                this.AllowUserToDeleteRows = false;
            }
        }
        #endregion
        #endregion

        #region 私有方法
        #region IsColumnExist
        private bool IsColumnExist(string columnName, ArrayList columnsToShow)
        {
            bool exist = false;
            for (int i = 0; i < columnsToShow.Count; i++)
            {
                if (columnsToShow[i].ToString() == columnName)
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }
        #endregion
        #endregion
    }
}
